package com.yexx.starter.security.basic;

import com.yexx.starter.security.basic.constant.SecurityConstants;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.security.access.AccessDeniedException;
import org.springframework.security.web.access.AccessDeniedHandler;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;

/**
 * Description: 自定义 访问拒绝handler
 *
 * @author: zuomin (myleszelic@outlook.com)
 * @date: 2020/10/30-10:32
 */
public class BasicAccessDeniedHandler implements AccessDeniedHandler {

    private Logger logger = LoggerFactory.getLogger(getClass());

    @Override
    public void handle(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, AccessDeniedException e) throws IOException, ServletException {
        logger.debug("操作没有权限", e);
        httpServletResponse.setContentType("application/json;charset=utf-8");
        httpServletResponse.setCharacterEncoding("utf-8");
        try(PrintWriter out = httpServletResponse.getWriter()){
            out.write(SecurityConstants.RETURN_JSON.DENIED_CODE);
            out.flush();
        }
    }
}
